package main

import (
	"context"
	"fmt"
	"log"
	"protobuf-learn/internal/loadbalancer"
	"protobuf-learn/internal/resolve"
	"protobuf-learn/proto"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/balancer"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/resolver"
)

func main() {
	ctx := context.Background()

	builder := &resolve.Builder{}
	resolver.Register(builder)

	group := map[string]string{
		"group-a": ":50051",
		"group-b": ":50052",
	}

	blBuilder := loadbalancer.NewBuilder(group, ":50053")
	balancer.Register(blBuilder)

	const serviceConfig = `{"loadBalancingPolicy": "ab_testing"}`

	conn, err := grpc.NewClient(fmt.Sprintf("%s://", builder.Scheme()),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(serviceConfig),
	)

	if err != nil {
		log.Fatal(err)
	}

	defer conn.Close()

	time.Sleep(10 * time.Second)

	client := proto.NewConfigServiceClient(conn)

	if err != nil {
		log.Fatal(err)
	}

	for _, group := range []string{"group-a", "group-b", "group-c"} {
		log.Printf("making request for group %q", group)

		res, err := client.GetServerAddress(
			metadata.AppendToOutgoingContext(ctx, "user-group", group),
			&proto.GetServerAddressRequest{},
		)

		if err != nil {
			log.Fatal(err)
		}

		log.Printf("response received for group %q from server: %s", group, res.GetAddress())
		time.Sleep(time.Second)
	}
}
